package com.wzy.musicplayer.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.wzy.musicplayer.R;
import com.wzy.musicplayer.data.music;
import com.wzy.musicplayer.data.musicList;
import com.wzy.musicplayer.model.PropertyBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    // 显示组件
    private ImageButton previousBtn;
    private ImageButton stopBtn;
    private ImageButton playOrPauseBtn;
    private ImageButton nextBtn;
    private ListView list;

    //歌曲列表对象
    private ArrayList<music> musicArrayList;

    //退出判断标记
    private static boolean isExit =false;

    //当前歌曲的序号,下标从0开始
    private int number = 0;

    //播放状态
    private int status;

    //广播接收器
    private StatusChangedReceiver receiver;
    private RelativeLayout root_Layout;
    private TextView text_Current;
    private TextView text_Duration;
    private SeekBar seekBar;
    private TextView textView;
    private Handler seekBarHandler;

    //当前歌曲的持续时间和当前位置，作用于进度条
    private int duration;
    private int time;

    //进度条控制常量
    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 2;

    //音量控制
    private TextView tv_vol;
    private SeekBar seekbar_vol;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
        registerListeners();
        initMusicList();
        initListView();
        checkMusicFile();
        duration = 0;
        time = 0;
        // 绑定广播接收器，可以接收广播
        bindStatusChangedReceiver();
        initSeekBarHandler();
        startService(new Intent(this, musicService.class));
        status = musicService.COMMAND_STOP;
    }

    private void initSeekBarHandler() {
        seekBarHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            //进度条前进1s
                            seekBar.setProgress(time);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改当前进度条的文本
                            text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        text_Current.setText("00:00");
                }
            }
        };
    }

    /**
     * 如果列表没有歌曲，则播放按钮不可用，并提醒用户
     */
    private void checkMusicFile() {
        if (musicArrayList.isEmpty()) {
            nextBtn.setEnabled(false);
            playOrPauseBtn.setEnabled(false);
            previousBtn.setEnabled(false);
            stopBtn.setEnabled(false);
            Toast.makeText(getApplicationContext(), "当前没有歌曲文件", Toast.LENGTH_SHORT).show();
        } else {
            nextBtn.setEnabled(true);
            previousBtn.setEnabled(true);
            previousBtn.setEnabled(true);
            stopBtn.setEnabled(true);
        }
    }

    /*初始化列表*/
    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (music Music : musicArrayList) {
            map = new HashMap<String, String>();
            map.put("musicName", Music.getMusicName());
            map.put("musicArtist", Music.getMusicArtist());
            list_map.add(map);
        }

        String[] from = new String[]{"musicName", "musicArtist"};
        int[] to = {R.id.tv_title_item, R.id.tv_artist_item};
        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview, from, to);
        list.setAdapter(simpleAdapter);
    }

    /*初始化音乐列表*/
    private void initMusicList() {
        musicArrayList = musicList.getMusicArray();
        //避免重复添加音乐
        if (musicArrayList.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[]{MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME}, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);
            if (mMusicCursor != null) {
                //标题
//                int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DISPLAY_NAME);
                int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
                //艺术家
                int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
                //总时长
                int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
                //路径
                int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

                for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor.moveToNext()) {
                    String strTitle = mMusicCursor.getString(indexTitle);
//                    strTitle.lastIndexOf()
                    String strArtist = mMusicCursor.getString(indexArtist);
                    String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                    String strPath = mMusicCursor.getString(indexPath);

                    if (strArtist.equals("<unknown>"))
                        strArtist = "无艺术家";
                    music Music = new music(strTitle, strArtist, strPath, strTotoalTime);
                    musicArrayList.add(Music);
                }
            }
        }
    }

    /**
     * 绑定广播接收器
     */
    private void bindStatusChangedReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(
                musicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }

    /*绑定按钮*/
    private void findViews() {
        previousBtn = (ImageButton) findViewById(R.id.preBtn);
        stopBtn = (ImageButton) findViewById(R.id.stopBtn);
        playOrPauseBtn = (ImageButton) findViewById(R.id.playBtn);
        nextBtn = (ImageButton) findViewById(R.id.nextBtn);
        list = (ListView) findViewById(R.id.listView1);
        textView = (TextView) findViewById(R.id.textView);
        seekBar = (SeekBar) findViewById(R.id.seekBar1);
        text_Current = (TextView) findViewById(R.id.textView1);
        text_Duration = (TextView) findViewById(R.id.textView2);
        root_Layout = (RelativeLayout) findViewById(R.id.relativeLayout1);
        tv_vol = (TextView) findViewById(R.id.main_tv_volumeText);
        seekbar_vol = (SeekBar) findViewById(R.id.main_sb_volumeBar);
    }

    /*为按钮添加点击事件*/
    private void registerListeners() {
        previousBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(musicService.COMMAND_PREVIOUS);
            }
        });
        stopBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(musicService.COMMAND_STOP);
            }
        });
        playOrPauseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (status) {
                    case musicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(musicService.COMMAND_PAUSE);
                        break;
                    case musicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(musicService.COMMAND_RESUME);
                        break;
                    case musicService.COMMAND_STOP:
                        sendBroadcastOnCommand(musicService.COMMAND_PLAY);
                        break;
                    default:
                        break;
                }
            }
        });
        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(musicService.COMMAND_NEXT);
            }
        });
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                number = position;
                sendBroadcastOnCommand(musicService.COMMAND_PLAY);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //进度条暂停移动
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (status != musicService.STATUS_STOPPED) {
                    time = seekBar.getProgress();
                    //更新文本
                    text_Current.setText(formatTime(time));
                    //发送广播给musicservice，执行跳转
                    sendBroadcastOnCommand(musicService.COMMAND_SEEK_TO);
                }
                if (status == musicService.STATUS_PLAYING) {
                    //发送广播给MusicService,执行跳转
                    sendBroadcastOnCommand(musicService.COMMAND_SEEK_TO);
                    //进度条恢复移动
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                }
                if (status == musicService.STATUS_STOPPED) {
                    sendBroadcastOnCommand(musicService.COMMAND_SEEK_TO);
                    sendBroadcastOnCommand(musicService.COMMAND_RESUME);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        sendBroadcastOnCommand(musicService.COMMAND_CHECK_IS_PLAYING);
        PropertyBean propetry = new PropertyBean(MainActivity.this);
        String theme = propetry.getTheme();
        //设置activity的主题
        setTheme(theme);
        audio_Control();
    }
    // 音量控制
    private void audio_Control() {
        //获取音乐管理器
        final AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        //设置调整当前音量大小只针对媒体音乐
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        //设置进度条的最大值
        final int max_progress = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekbar_vol.setMax(max_progress);
        //获取当前音量
        int progress = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekbar_vol.setProgress(progress);
        tv_vol.setText("音量："+(progress*100/max_progress)+"%");
        seekbar_vol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
                tv_vol.setText("音量："+(arg1*100/max_progress)+"%");
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,arg1,AudioManager.FLAG_PLAY_SOUND);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    /**
     * 发送命令，控制音乐播放，参数在musicService类中定义
     */
    private void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(musicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        //根据不同的命令，封装不同的数据
        switch (command) {
            case musicService.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case musicService.COMMAND_SEEK_TO:
                intent.putExtra("time", time);
                break;
            case musicService.COMMAND_PREVIOUS:
            case musicService.COMMAND_NEXT:
            case musicService.COMMAND_PAUSE:
            case musicService.COMMAND_STOP:
            case musicService.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    /**
     * 内部类，用于播放器状态更新的接收广播
     */
    class StatusChangedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String musicName = intent.getStringExtra("musicName");
            String musicArtist = intent.getStringExtra("musicArtist");
            MainActivity.this.textView.setText(musicArtist + " - " + musicName);
            //获取播放器状态
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case musicService.STATUS_PLAYING:
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    number = intent.getIntExtra("number", number);
                    list.setSelection(number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                    text_Duration.setText(formatTime(duration));
                    playOrPauseBtn.setBackgroundResource(R.drawable.pause);
                    //设置textview文字，提示已经播放的歌曲
//                    Toast.makeText(MainActivity.this,intent.getStringExtra("musicArtist"), Toast.LENGTH_SHORT).show();
                    MainActivity.this.setTitle("正在播放:" + musicName + " - " + musicArtist);
                    break;
                case musicService.STATUS_PAUSED:
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    playOrPauseBtn.setBackgroundResource(R.drawable.play);
                    break;
                case musicService.STATUS_STOPPED:
                    time = 0;
                    duration = 0;
                    text_Current.setText(formatTime(time));
                    text_Duration.setText(formatTime(duration));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("GracePlayer");
                    textView.setText("");
                    playOrPauseBtn.setBackgroundResource(R.drawable.play);
                    break;
                case musicService.STATUS_COMPLETED:
                    number = intent.getIntExtra("number", 0);
                    if (number == musicList.getMusicArray().size() - 1)
                        sendBroadcastOnCommand(musicService.STATUS_STOPPED);
                    else
                        sendBroadcastOnCommand(musicService.COMMAND_NEXT);
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("GracePlayer");
                    textView.setText("");
                    sendBroadcastOnCommand(musicService.COMMAND_NEXT);
                    break;
                default:
                    break;

            }
        }
    }

    @Override
    protected void onDestroy() {
        if (status == musicService.STATUS_STOPPED) {
            stopService(new Intent(this, musicService.class));
        }
        super.onDestroy();
    }

    //格式化时间
    private String formatTime(int msec) {
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        String secondString;
        if (minute < 10) {
            minuteString = "0" + minute;
        } else {
            minuteString = "" + minute;
        }
        if (second < 10) {
            secondString = "0" + second;
        } else {
            secondString = "" + second;
        }
        return minuteString + ":" + secondString;
    }

    //设置Activity的主题，包括修改背景图片等等
    private void setTheme(String theme) {
        if ("彩色".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_color);
        } else if ("花朵".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_digit_flower);
        } else if ("群山".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_mountain);
        } else if ("小狗".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_running_dog);
        } else if ("冰雪".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_snow);
        } else if ("女孩".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_music_girl);
        } else if ("朦胧".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_blur);
        }
    }

    //创建菜单
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    //处理菜单点击事件
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_theme:
                new AlertDialog.Builder(this).setTitle("请选择主题").setItems(R.array.theme, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        String[] themes = MainActivity.this.getResources().getStringArray(R.array.theme);
//                        setTheme(themes[which]);
                        //获取array.xml定义主题的名称
                        String theme = PropertyBean.THEMES[which];
                        //设置主题
                        setTheme(theme);
                        //保存设置的主题
                        PropertyBean property = new PropertyBean(MainActivity.this);
                        property.setAndSaveTheme(theme);
                    }
                }).show();
                break;
            case R.id.menu_about:
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("GRacePlayer")
                        .setMessage(R.string.about2)
                        .show();
                break;
            case R.id.menu_quit:
                new AlertDialog.Builder(this)
                        .setTitle("提示").
                        setMessage(R.string.quit).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        System.exit(0);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                }).show();
        }
        return super.onOptionsItemSelected(item);
    }

    //重写onkeyDown函数
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int progress;
        switch (keyCode){
            case KeyEvent.KEYCODE_BACK:
                exitByDoubleClick();
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                progress = seekbar_vol.getProgress();
                if(progress != 0)
                    seekbar_vol.setProgress(progress-1);
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                progress = seekbar_vol.getProgress();
                if(progress != seekbar_vol.getMax())
                    seekbar_vol.setProgress(progress+1);
                return true;
            default:
                break;
        }
        return false;
    }

    private void exitByDoubleClick() {
        Timer timer = null;
        if (isExit == false){
            isExit = true; //准备退出
            Toast.makeText(this,"再点击一次退出程序",Toast.LENGTH_SHORT).show();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            },2000);
        }
        else {
            System.exit(0);
        }
    }
}
